package io.github.talelin.latticy.service.impl.ag;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.github.talelin.latticy.dto.ag.jcunit.CreateOrUpdateJcUnitDTO;
import io.github.talelin.latticy.mapper.ag.JcUnitMapper;
import io.github.talelin.latticy.model.ag.JcUnitDO;
import io.github.talelin.latticy.service.ag.JcUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class JcUnitServiceImpl implements JcUnitService {
    @Autowired
    JcUnitMapper unitMapper;

    @Override
    public JcUnitDO getById(int id) {
        return unitMapper.selectById(id);
    }

    @Override
    public List<JcUnitDO> getJcUnits() {
        QueryWrapper<JcUnitDO> wrapper = new QueryWrapper<>();
        wrapper.select().orderByDesc("update_time");
        return unitMapper.selectList(wrapper);
    }

    @Override
    public boolean deleteById(int id) {
        return unitMapper.deleteById(id)>0;
    }

    @Override
    public boolean createJcUnit(CreateOrUpdateJcUnitDTO validator) {
        JcUnitDO jcUnit = new JcUnitDO();
        jcUnit.setIdSelfDefined(validator.getId_self_defined());
        jcUnit.setName(validator.getName());
        jcUnit.setPhone(validator.getPhone());
        jcUnit.setComment(validator.getComment());
        jcUnit.setIsUse(validator.getIs_use());
        jcUnit.setHigherLevelUnit(validator.getHigher_level_unit());
        return unitMapper.insert(jcUnit) > 0;
    }

    @Override
    public boolean updateJcUnit(JcUnitDO jcUnitDO, CreateOrUpdateJcUnitDTO validator) {
        jcUnitDO.setIdSelfDefined(validator.getId_self_defined());
        jcUnitDO.setName(validator.getName());
        jcUnitDO.setPhone(validator.getPhone());
        jcUnitDO.setComment(validator.getComment());
        jcUnitDO.setIsUse(validator.getIs_use());
        jcUnitDO.setHigherLevelUnit(validator.getHigher_level_unit());
        return unitMapper.updateById(jcUnitDO) > 0;
    }

    @Override
    public IPage<JcUnitDO> getUnitByPage(Page<JcUnitDO> pager) {
        QueryWrapper<JcUnitDO> wrapper = new QueryWrapper<>();
        wrapper.select().orderByDesc("update_time");
        IPage<JcUnitDO> iPage =unitMapper.selectPage(pager, wrapper);
        return iPage;
    }

    @Override
    public IPage<JcUnitDO> searchUnitByKeyword(Page<JcUnitDO> pager, String keyword) {
        QueryWrapper<JcUnitDO> wrapper = new QueryWrapper<>();
        wrapper.like("id_self_defined",keyword)
                .or().like("name", keyword)
                .or().like("higher_level_unit", keyword)
                .or().like("is_use", keyword);
        IPage<JcUnitDO> iPage = unitMapper.selectPage(pager, wrapper);
        return iPage;
    }
}
